package com.example.demo.controller;

import com.example.demo.entity.Semester;
import com.example.demo.service.SemesterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/semesters")
public class SemesterController {

    @Autowired
    private SemesterService semesterService;

    // POST /api/semesters - 创建新学期
    @PostMapping
    public ResponseEntity<?> createSemester(@RequestBody Semester semester) {
        try {
            Semester newSemester = semesterService.createSemester(semester);
            return new ResponseEntity<>(newSemester, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("学期创建失败: " + e.getMessage());
        }
    }

    // GET /api/semesters - 获取所有学期
    @GetMapping
    public List<Semester> getAllSemesters() {
        return semesterService.findAllSemesters();
    }

    // GET /api/semesters/{id} - 根据ID获取单个学期
    @GetMapping("/{id}")
    public ResponseEntity<Semester> getSemesterById(@PathVariable("id") Integer semesterId) {
        return semesterService.findSemesterById(semesterId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // PUT /api/semesters/{id} - 更新学期信息
    @PutMapping("/{id}")
    public ResponseEntity<?> updateSemester(
            @PathVariable("id") Integer semesterId,
            @RequestBody Semester semesterDetails
    ) {
        semesterDetails.setId(semesterId); // 确保ID一致

        if (semesterService.updateSemester(semesterDetails)) {
            return ResponseEntity.ok("学期信息更新成功");
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // DELETE /api/semesters/{id} - 删除学期
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteSemester(@PathVariable("id") Integer semesterId) {
        if (semesterService.deleteSemester(semesterId)) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}